package server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class HttpServer {
    //存放静态页面的位置
    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
    //停机命令
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    //是否停机
    private boolean shutdown = false;
    public static final int PORT = 6688;
    public static void main(String[] args) {
        new HttpServer().await();
    }

    public void await() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(PORT, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while (!shutdown) {
            try {
                Socket socket = serverSocket.accept();
                InputStream input = socket.getInputStream();
                OutputStream output = socket.getOutputStream();
                //创建request对象
                Request request = new Request(input);
                request.parse();
                System.out.println("request:==================================");
                System.out.println(request.getRequest());
                System.out.println("==========================================");
                System.out.println("uri:" + request.getUri());
                //创建response对象
                Response response = new Response(output);
                response.setRequest(request);
                response.sendStaticResource();
                socket.close();
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }

        }
    }
}
